package com.hzhh123.download;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.hzhh123.download.adapter.FileAdapter;
import com.hzhh123.download.model.File;
import com.hzhh123.download.service.DownloadService;
import com.hzhh123.download.utils.db.DbHelper;
import com.hzhh123.download.utils.notify.NotifyUtils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 多文件列表下载
 * bug 有一定的几率出现下载超时timeout,内存没有及时释放导致,未解决
 */
public class MoreDownloadActivity extends BaseAcitivity {
    private static final String TAG = "MoreDownloadActivity";
    private int REQUEST_CODE_EXTERNAL_STORAGE = 20;
    private RecyclerView recyclerView;
    private Toolbar toolbar;
    private FileAdapter fileAdapter;


    private HashMap<String, DownloadReceiver> downloadReceiverMap = new HashMap<>();
    private List<File> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_download);
        initToolbar();
        checkExtrnalStorage();
        getData();
        recyclerView = findViewById(R.id.recyclerView);
        fileAdapter = new FileAdapter(list, this);
        recyclerView.setAdapter(fileAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        fileAdapter.setOnItemClickListener(new FileAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, int type) {
                File file = list.get(position);
                Intent intent = null;
                switch (type) {
                    case File.DOWNLOAD_PAUSE://暂停->开始
                        file.setSizeStr("请稍等");
                        file.setSpeed("");
                        fileAdapter.notifyItemChanged(position);
                        intent = new Intent(MoreDownloadActivity.this, DownloadService.class);
                        intent.putExtra("filename", file.getFileName());
                        intent.putExtra("url", file.getUrl());
                        intent.putExtra("id", file.getId());
                        intent.putExtra("seq", file.getSeq());
                        startService(intent);
                        file.setStatus(File.DOWNLOAD_PROCEED);
                        break;
                    case File.DOWNLOAD_PROCEED://开始->暂停
                        System.out.println("开始->暂停");
                        file.setStatus(File.DOWNLOAD_PAUSE);
                        MyApplication.downloadTaskHashMap.get(file.getId()).cancel();
                        break;
                    case File.DOWNLOAD_ERROR://出错
                        file.setStatus(File.DOWNLOAD_PROCEED);
                        file.setSpeed("---");
                        fileAdapter.notifyItemChanged(position);
                        intent = new Intent(MoreDownloadActivity.this, DownloadService.class);
                        intent.putExtra("filename", file.getFileName());
                        intent.putExtra("url", file.getUrl());
                        intent.putExtra("id", file.getId());
                        intent.putExtra("seq", file.getSeq());
                        startService(intent);
                        break;
                    case File.DOWNLOAD_COMPLETE://完成
                        Toast.makeText(MoreDownloadActivity.this, "完成", Toast.LENGTH_SHORT).show();
                        break;
                    case File.DOWNLOAD_REDYA://准备下载 ->开始
                        file.setSizeStr("请稍等");
                        file.setSpeed("");
                        fileAdapter.notifyItemChanged(position);
                        intent = new Intent(MoreDownloadActivity.this, DownloadService.class);
                        intent.putExtra("filename", file.getFileName());
                        intent.putExtra("url", file.getUrl());
                        intent.putExtra("id", file.getId());
                        intent.putExtra("seq", file.getSeq());
                        startService(intent);
                        file.setStatus(File.DOWNLOAD_PROCEED);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onItemLongClick(View view, int position, int type) {
                Toast.makeText(MoreDownloadActivity.this, "长按" + type, Toast.LENGTH_SHORT).show();
            }

        });
    }

    private void initToolbar(){
        toolbar = findViewById(R.id.toolbar);
        //设置标题和颜色
        toolbar.setTitle("下载");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        Menu menu = toolbar.getMenu();
        menu.add("设置").setIcon(R.drawable.setting_white).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.getItem(0).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                startActivity(new Intent(MoreDownloadActivity.this,DownloadSettingActivity.class));
                return false;
            }
        });
        //返回菜单
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    private void getData() {
        List<String> downloadedFileIds = getDownloadedFileIds();
        Log.d(TAG, "getData: "+downloadedFileIds);
        List<File> fileList = selectDownloadedFiles();
        for (int i = 0; i < 20; i++) {
            File file = new File();
            file.setId(""+i);
            file.setSeq(i);
            file.setFileName(i + ".apk");
            if(downloadedFileIds.contains(file.getId())){
                File file1 = fileList.get(downloadedFileIds.indexOf(file.getId()));
                System.out.println(file1);
                Log.d(TAG, "getData: "+file1.getStatus());
                file.setStatus(file1.getStatus());
                file.setSizeStr(file1.getSizeStr());
                file.setCreateTime(file1.getCreateTime());
            }else {
                file.setStatus(File.DOWNLOAD_REDYA);
                file.setCreateTime(new Date());
            }
            file.setFileType(".doc");
            file.setUrl("https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk");

            list.add(file);
            IntentFilter filter = new IntentFilter();
            DownloadReceiver receiver = new DownloadReceiver();
            filter.addAction("com.hzhh123.download" + file.getId());
            registerReceiver(receiver, filter);
            downloadReceiverMap.put(file.getId(), receiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadReceiverMap.size() > 0) {
            for (String key : downloadReceiverMap.keySet()) {
                unregisterReceiver(downloadReceiverMap.get(key));
            }
            downloadReceiverMap.clear();
        }
    }

    class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            for (int i = 0; i < list.size(); i++) {
                File file = list.get(i);
                if (intent.getAction().equals("com.hzhh123.download" + file.getId())) {
                    String speedS = intent.getStringExtra("speed");
                    String sizeS = intent.getStringExtra("size");
                    String totalSize = intent.getStringExtra("totalSize");
                    int pencent = intent.getIntExtra("percent", 0);
                    int status = intent.getIntExtra("status", 0);
                    if (status == File.DOWNLOAD_PROCEED) {
                        file.setSpeed(speedS);
                        file.setProgress(pencent);
                        file.setSizeStr(sizeS);
                    }
                    if (status == File.DOWNLOAD_COMPLETE) {//完成
                        file.setStatus(File.DOWNLOAD_COMPLETE);
                        file.setProgress(pencent);
                        file.setSizeStr(totalSize);
                        MyApplication.downloadTaskHashMap.remove(file.getId());
                    }
                    if (status == File.DOWNLOAD_ERROR) {
                        MyApplication.downloadTaskHashMap.get(file.getId()).cancel();
                        file.setStatus(File.DOWNLOAD_ERROR);
                    }
                    fileAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    /**
     * 检查外部scard读写权限
     */
    private void checkExtrnalStorage(){
        //首先判断用户手机的版本号 如果版本大于6.0就需要动态申请权限
        //如果版本小于6.0就直接去扫描二维码
        if(Build.VERSION.SDK_INT>23){
            //说明是android6.0之前的
            //添加动态权限申请
            //1.定义一个数组，用来装载申请的权限
            String[] permissons={
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
            //2.判断这些权限有没有申请，没有申请的话，就把没有申请的权限放到一个数组里面
            ArrayList<String> deniedPermissions=new ArrayList<String>();
            for(String permission:permissons){
                int i = ContextCompat.checkSelfPermission(this, permission);
                if(PackageManager.PERMISSION_DENIED==i){
                    //说明权限没有被申请
                    deniedPermissions.add(permission);
                }
            }
            if(deniedPermissions.size()==0){
                //说明是android6.0之前的
                return;
            }
            //当你不知道数组多大的时候，就可以先创建一个集合，然后调用集合的toArray方法需要传递一个数组参数，这个数组参数的长度
            //设置成跟集合一样的长度
            String[] strings = deniedPermissions.toArray(new String[permissons.length]);
            //3.去申请权限
            ActivityCompat.requestPermissions(this,strings,REQUEST_CODE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 查询已下载的文件
     * @return
     */
    private List<com.hzhh123.download.model.File>selectDownloadedFiles(){
        List<com.hzhh123.download.model.File>fileList=new ArrayList<>();
        DbManager db = DbHelper.getDbManager();
        try {
            fileList=db.selector(com.hzhh123.download.model.File.class).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return fileList;
    }

    private List<String>getDownloadedFileIds(){
        List<String>ids=new ArrayList<>();
        List<File> fileList = selectDownloadedFiles();
        if(fileList!=null) {
            for (File file : fileList) {
                ids.add(file.getId());
            }
        }
        return ids;
    }

    /**
     * 下载暂停
     * @param fileName
     * @param seq
     */
    private void createDownloadErrorNotification(String fileName,int seq){
        Log.d(TAG, "createDownloadErrorNotification: ");
        RemoteViews remoteViews= new RemoteViews(getPackageName(), R.layout.download_pause_notice);
        remoteViews.setTextViewText(R.id.file_name,fileName);
        remoteViews.setTextViewText(R.id.tip,"下载暂停");
        NotifyUtils notifyUtils = new NotifyUtils(this, "chanel1","low1");
        notifyUtils.clear();
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                0, new Intent(this,MoreDownloadActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
        notifyUtils.notifyCustomView(remoteViews,contentIntent,
                R.mipmap.file,0,"文件下载",seq+10002,false,false,false);
    }
}
